import './public-path'
import micro from '@/utils/event'
import { createApp } from 'vue'
import App from './App.vue'
import routes from './router'
import { createRouter, createWebHistory } from 'vue-router'
import store from './store'

let router = null
let instance = null
let history = null

function render (props = {}) {
  // 有props代表是qiankun环境
  const { container, onGlobalStateChange, setGlobalState } = props
  // props.path 即主应用传过来path 保持一致
  history = createWebHistory(window.__POWERED_BY_QIANKUN__ ? props.path : '/')
  router = createRouter({
    history,
    routes: routes
  })
  instance = createApp(App)
  /* 将主应用props的onGlobalStateChange，setGlobalState方法挂载到全局 */
  if (window.__POWERED_BY_QIANKUN__) {
    instance.config.globalProperties.$onGlobalStateChange = onGlobalStateChange
    instance.config.globalProperties.$setGlobalState = setGlobalState
    instance.config.globalProperties.$micro = micro
    instance.config.globalProperties.$parentRouter = props.router
  }
  instance.use(router)
  instance.use(store)
  instance.mount(container ? container.querySelector('#app') : '#app')
}

if (!window.__POWERED_BY_QIANKUN__) {
  // 不是qiankun环境确保独立运行
  render()
}

export async function bootstrap (props) {
  // 启动
  console.log('bootstrap', props)
  if (props.onMicroLoaded) {
    props.onMicroLoaded({ $micro: micro })
  }
}
export async function mount (props) {
  console.log('mount', props)
  // 挂载  
  render(props)
}
export async function unmount () {
  // 卸载
  instance.unmount()
  instance._container.innerHTML = ''
  instance = null
  router = null
  history.destroy()
}
// console.log('window', window)
